package cn.ren.security;

import cn.ren.pojo.Permission;
import cn.ren.pojo.Role;
import cn.ren.pojo.User;
import cn.ren.service.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @program: itcast_health
 * @description: 用户登录认证
 * @author: ren
 * @create: 2020-03-03 10:14
 **/
@Component
public class SpringSecurityUserService implements UserDetailsService {
    //还是通过Dubbo远程调用服务
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = null;
        try {
            user = userService.findUserByName(username);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
//        if (user == null){
//            return null;
//        }
        //将查询到的用户信息保存到security框架中的User对象中,权限相关的放到list里
        List<GrantedAuthority> list = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //将角色保存到list
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //将权限保存到list
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        return new org.springframework.security.core.userdetails.User(
                username,
                user.getPassword(),
                list);
    }
}
